import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import * as API from '../api/Http'

let initialState={
    shezhilist:[]
}
const crmslice = createSlice({
  name: "crm",
  initialState,
  reducers: {
    getshezhi(state,action){
        state.shezhilist=action.payload
    },
    delshezhi(state,action){
        state.shezhilist=state.shezhilist.filter(item=>{
            return item.id!==action.payload
        })
    },
    addshezhi(state,action){
        state.shezhilist.push(action.payload)
    },
    updateshezhi(state,action){
        let i=state.shezhilist.findIndex(item=>{
            return item.id==action.payload.id
        })
        state.shezhilist[i]=action.payload
    }
  },
});

export const actionFn = crmslice.actions;
export default crmslice.reducer;

export let async_getshezhi=createAsyncThunk('async_getshezhi',
    async(_,store)=>{
        let res=await API.shezhi()
        store.dispatch(actionFn.getshezhi(res))
    }
)

export let async_delshezhi=createAsyncThunk('async_delshezhi',
    async(id,store)=>{
        await API.del(id)
        store.dispatch(actionFn.delshezhi(id))
    }
)

export let async_addshezhi=createAsyncThunk('async_addshezhi',
    async(obj,store)=>{
        let res=await API.add(obj)
        store.dispatch(actionFn.addshezhi(res))
    }
)

export let async_updateshezhi=createAsyncThunk('async_updateshezhi',
    async(obj,store)=>{
        let res=await API.update(obj)
        store.dispatch(actionFn.updateshezhi(res))
    }
)